//
//  ST_RecentCallsViewModel.swift
//  btvideo
//
//  Created by mac on 2021/9/9.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa

class ST_RecentCallsViewModel {
    
    /// 最近通话列表
    let recentCalls = BehaviorRelay<[ST_RecentCallModel]>(value: [])
    
    /// 刷新完成
    let onRefreshed = PublishSubject<Bool>()
    
    /// 加载更多完成
    let onMoreLoaded = PublishSubject<Bool>()
    
    /// 错误
    let onError = PublishSubject<Error>()
    
    /// 当前页码
    var currentPage = 1
    
    /// 刷新列表
    func refresh_data() {
        currentPage = 1
        fetchData()
    }
    
    /// 获取更多数据
    func load_more_data() {
        currentPage += 1
        fetchData()
    }
    
    /// 获取列表数据
    func fetchData() {
        JVrequest(PH.recentCallsListApi, parameters: ["page": currentPage, "size": 20], success: { [weak self] json in
            let models = json["data"].arrayValue.compactMap { ST_RecentCallModel.deserialize(from: $0.dictionary) }
            if (self?.currentPage ?? 1) > 1 {
                var temp = self?.recentCalls.value ?? []
                temp.append(contentsOf: models)
                self?.recentCalls.accept(temp)
                self?.onMoreLoaded.onNext(models.count >= 20)
            } else {
                self?.recentCalls.accept(models)
                self?.onRefreshed.onNext(models.count >= 20)
            }
        }, failure: { [weak self] (code, error) in
            guard let self = self else { return }
            self.currentPage = max(1, self.currentPage - 1)
            if self.currentPage > 1 {
                self.onMoreLoaded.onNext(false)
            } else {
                self.onRefreshed.onNext(false)
            }
            self.onError.onNext(ST_MyError.description(error))
        })
    }
    
    /// 回拨
    /// - Parameter id: 数据ID
    func recall(id: Int) {
        JVrequest(PH.reCallApi, parameters: ["record_id": id], success: { _ in }, failure: { _,_ in })
    }
}
